import 'dart:async';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:search_people/utils/fun_util.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../bean/city.dart';
import '../../../bean/search/hot_people.dart';
import '../../../entrance/route/routes.dart';
import '../../../utils/component/component.dart';
import '../../../utils/httputils/net_api.dart';
import '../../../utils/keys.dart';
import '../../../utils/storage.dart';
import '../subs/person_detail/models/person_dynamic_model.dart';
import 'state.dart';

class HomeLogic extends GetxController with GetSingleTickerProviderStateMixin {
  final HomeState state = HomeState();
  @override
  void onInit() {
    state.rc = RefreshController();
    state.tabCtrl = TabController(length: 3, vsync: this);
    initData();

    super.onInit();

    var winedGuide = SpUtil().getBool(StorageKeys.firstGuide);
    if (winedGuide != true) {
      Timer(const Duration(seconds: 1), () {
        /// start the intro
        state.intro.start(Get.context!);
      });

      SpUtil().setBool(StorageKeys.firstGuide, true);
    }
  }

  void onRefresh() {
    state.pageIndex = 0;
    requestData();
  }

  void onLoading() {
    state.pageIndex++;
    postDynamic();
  }

  void requestData() {
    getHotData();
    postDynamic();
  }

  @override
  void onReady() {
    super.onReady();
    requestData();
  }

  void refreshMenuStore(HomeMenuType type) {
    String str = SpUtil().getStr(StorageKeys.recent_menu);
    var list = str.split(',');
    if (type != HomeMenuType.all && !list.contains(type.val.toString())) {
      list.add(type.val.toString());
      var _str = list.join(',');
      SpUtil().setStr(StorageKeys.recent_menu, _str);
    }
  }

  void actionMenuItem(HomeMenuType type) {
    refreshMenuStore(type);
    switch (type) {
      case HomeMenuType.searchSuper:
        Get.toNamed(RouterPath.super_search);
        break;
      case HomeMenuType.searchArea:
        actionSearchCity(0);
        break;
      case HomeMenuType.searchShcool:
        actionSearchSchool();
        break;
      case HomeMenuType.searchBirthPlace:
        actionSearchCity(1);
        break;
      case HomeMenuType.searchBirthDay:
        actionSearchBirthday();
        break;
      case HomeMenuType.searchJob:
        actionSearchJob();
        break;
      case HomeMenuType.function:
        // Get.toNamed(RouterPath.web_view, parameters: {
        //   'url':
        //       'https://docs.google.com/viewer?url=http://www.africau.edu/images/default/sample.pdf',
        // });
        break;
      default:
        Get.toNamed(RouterPath.menu_all);
    }
  }

  void initData() {
    var items = HomeMenuType.searchItems
      ..add(HomeMenuType.function)
      ..add(HomeMenuType.all);
    state.menuItems = items
        .map((e) => MenuItem()
          ..title = e.title
          ..icon = e.icon
          ..onTap = () {
            actionMenuItem(e);
          })
        .toList();
  }

  //获取热搜人物
  void getHotData() async {
    var resultData = await Api.hot_people();
    List data = resultData.data;
    state.hots = data.map((e) => HotPeople.fromJson(e)).toList();
    update();
  }

  //

  //获取工作动态
  void postDynamic() async {
    var resultData = await HomeApi.postDynamicList(pageIndex: state.pageIndex);
    List data = resultData.data['records'];
    state.dynamics = data
        .asMap()
        .map(
          (key, e) => MapEntry(
            key,
            PersonDynamicModel.fromJson(e)..labelColors = _getColors(key),
          ),
        )
        .values
        .toList();

    update();
  }

  List<Color> _getColors(int idx) {
    switch (idx) {
      case 0:
        return [Colors.green, Colors.red, Colors.purple];
      case 1:
        return [Colors.deepPurpleAccent, Colors.blue, Colors.green];
      default:
        return [Colors.green, Colors.red, Colors.purple];
    }
  }

  // type 0 按区域  1 按籍贯
  void actionSearchCity(int type) async {
    if (state.cityList == null) {
      var res = await Api.getCityList();
      List cityData = res.data;
      List<CityModel> cityList =
          cityData.map((e) => CityModel.fromJson(e)).toList();
      List<BrnSelectCityModel> citys = [];
      for (var e in cityList) {
        if (!isZeroList(e.citys)) {
          for (var e1 in e.citys!) {
            citys.add(BrnSelectCityModel(
                name: e1.name, cityCode: e1.id, tag: e.name));
          }
        }
      }
      state.cityList = citys;
    }
    Get.to(() => BrnSingleSelectCityPage(
          hotCityList: [],
          cityList: state.cityList,
          onValueChanged: (value) {
            Future.delayed(const Duration(milliseconds: 200)).then((_) {
              Get.toNamed(
                RouterPath.search_page,
                parameters: type == 0 ? {'type': 'city'} : {},
                arguments: type == 0
                    ? {'regionCityId': value.cityCode}
                    : {
                        'hometownId': value.cityCode,
                        'hometownName': value.name,
                      },
              );
            });
          },
        ));
  }

  void actionSearchSchool() async {
    if (state.schoolList == null) {
      var res = await Api.getSchoolList();
      List sl = res.data;
      state.schoolList = sl
          .map(
            (e) => BrnSelectCityModel(
              name: e['name'].toString(),
              cityCode: e['id'].toString(),
            ),
          )
          .toList();
    }
    Get.to(() => BrnSingleSelectCityPage(
          hotCityList: [],
          cityList: state.schoolList,
          onValueChanged: (value) {
            Future.delayed(const Duration(milliseconds: 200)).then((_) {
              Get.toNamed(
                RouterPath.search_page,
                arguments: {'schoolId': value.cityCode},
              );
            });
          },
        ));
  }

  void actionSearchBirthday() async {
    var res = await Get.toNamed(RouterPath.search_birthday);
    if (res != null) {
      Get.toNamed(
        RouterPath.search_page,
        arguments: {'birthDateStr': res},
      );
    }
  }

  void actionSearchJob() async {
    if (state.schoolList == null) {
      var res = await HomeApi.getJobs();
      List jobData = res.data;
      List<CityModel> jobList =
          jobData.map((e) => CityModel.fromJson(e)).toList();
      List<BrnSelectCityModel> jobs = [];
      for (var e in jobList) {
        if (!isZeroList(e.citys)) {
          for (var e1 in e.citys!) {
            jobs.add(BrnSelectCityModel(
                name: e1.name, cityCode: e1.id, tag: e.name));
          }
        }
      }
      state.jobList = jobs;
    }
    Get.to(() => BrnSingleSelectCityPage(
          hotCityList: [],
          cityList: state.jobList,
          onValueChanged: (value) {
            Future.delayed(const Duration(milliseconds: 200)).then((_) {
              Get.toNamed(
                RouterPath.search_page,
                arguments: {'jobId': value.cityCode},
              );
            });
          },
        ));
  }
}
